package com.zhuoya.healthcard.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.format.DateFormat;
import android.util.Log;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

public class EPLog {
    private static boolean isDebuggable = true;

    private static FileWriter logfile = null;

	/*
	public static void initLogFile(){
		try {
			logfile = new FileWriter(new File("/mnt/sdcard/EPSample_log.txt"), true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	*/

	/*
	public static void closeLogFile(){
		if(logfile != null){
			try {
				logfile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			logfile = null;
		}
	}
	*/

    public static boolean isDebuggable(Context context) {
        PackageManager manager = context.getPackageManager();
        ApplicationInfo appInfo = null;
        try {
            appInfo = manager.getApplicationInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            isDebuggable = false;
        }
        if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE) {
            isDebuggable = true;
        }
        // isDebuggable = false;

        return isDebuggable;
    }

    static void writeLogFile(String text) {
        if (logfile != null) {
            try {
                String curTime = DateFormat.format("yyyy/MM/dd, E, kk:mm:ss", Calendar.getInstance()).toString();
                ;
                logfile.write("(" + curTime + ")" + text + "\n");
                logfile.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static final void d(String tag, String msg) {
        if (isDebuggable == true) {
            Log.d(tag, msg);
        }
        writeLogFile("D:" + tag + ":" + msg);
    }

    public static final void e(String tag, String msg) {
        if (isDebuggable == true) {
            Log.e(tag, msg);
        }
        writeLogFile("E:" + tag + ":" + msg);
    }

    public static final void i(String tag, String msg) {
        if (isDebuggable == true) {
            Log.i(tag, msg);
        }
        writeLogFile("I:" + tag + ":" + msg);
    }

    public static final void v(String tag, String msg) {
        if (isDebuggable == true) {
            Log.v(tag, msg);
        }
        writeLogFile("V:" + tag + ":" + msg);
    }

    public static final void w(String tag, String msg) {
        if (isDebuggable == true) {
            Log.w(tag, msg);
        }
        writeLogFile("W:" + tag + ":" + msg);
    }
}
